#!/bin/bash
#NAUTILUS_SCRIPT_CURRENT_URI

. $(dirname "$0")/includepath

#FFMPEG="/media/LinuxData/Development64/local/bin/ffmpeg -v 0 -qscale 1 -i"
FFMPEG="${FFMPEGPATH} -v 0 -qscale 1 -i "
KUTE="${KUTEPATH}/bin/kute"
TOEXT=".mp3"

if [ "$(tty)" = "not a tty" ];then
	FROMWHERE="NAUTILUS"
else
	FROMWHERE="TERMINAL"

fi

get_metatags ()
{
#Just in case no mete tags use folder names

	if [ X"$TITLE" = X ]
		then TITLE=$(basename "$1" $EXT)
	fi

	if [ X"$ALBUM" = X ]
		then ALBUM=$(basename "$(dirname "$1")")
	fi

	if [ X"$ARTIST" = X ]
		then ARTIST=$(basename "$(dirname "$(dirname "$1")")")
	fi

	ARTIST=$($KUTE  "$1" |grep -i artist=|cut -d \= -f 2)
	ALBUM=$($KUTE  "$1" |grep -i album=|cut -d \= -f 2)
	TITLE=$($KUTE  "$1" |grep -i title=|cut -d \= -f 2)
	TRACK=$($KUTE  "$1" |grep -i track=|cut -d \= -f 2)
	TOTALTRACKS=$($KUTE  "$1" |grep -i totaltracks=|cut -d \= -f 2)
	CD=$($KUTE  "$1" |grep -i cd=|cut -d \= -f 2)
	GENRE=$($KUTE  "$1" |grep -i genre=|cut -d \= -f 2)
	YEAR=$($KUTE  "$1" |grep -i year=|cut -d \= -f 2)
	COMPILATION=$($KUTE  "$1" |grep -i compilation=|cut -d \= -f 2)
	COMPOSER=$($KUTE  "$1" |grep -i composer=|cut -d \= -f 2)
	COMMENT=$($KUTE  "$1" |grep -i comment=|cut -d \= -f 2)
}

cd "$1"

touch /tmp/alltomp3.log

find -iname "*.flac" -o -iname "*.m4a" -o -iname "*.aac" | while read
	do
		INFILE="$PWD"${REPLY#.}
		FILETYPE=$(file -b "$INFILE")
		
		get_metatags "$INFILE"

		OUTFILE=${INFILE%.m4a}
		OUTFILE=${OUTFILE%.flac}

		OUTFILE="$OUTFILE"${TOEXT}
		echo "Converting $INFILE to $OUTFILE..." >> /tmp/alltomp3.log
		if [ $FROMWHERE = NAUTILUS ];then
			$FFMPEG "$INFILE" "$OUTFILE" 2>&1 0</dev/null |zenity --progress --pulsate --auto-kill --title="Decoding" --text="Decoding ${INFILE//&//}" --auto-close
			
		else
			echo "Converting $INFILE to $OUTFILE..."
			$FFMPEG "$INFILE" "$OUTFILE" 2>/dev/null 0</dev/null
		fi
		echo "Finished" >> /tmp/alltomp3.log
		$KUTE --artist="$ARTIST"  --album="$ALBUM" --title="$TITLE" --track="$TRACK" --total-tracks="$TOTALTRACKS" --cd="$CD" --compilation="$COMPILATION" --year="$YEAR" --genre="$GENRE" --composer="$COMPOSER" --comment="$COMMENT" "$OUTFILE"
		rm "$INFILE"
	done

